import { Injectable } from '@nestjs/common';
import { CreateDictTypeDto } from './dto/create-dict-type.dto';
import { UpdateDictTypeDto } from './dto/update-dict-type.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DictType } from './entities/dict-type.entity';
import { Like, Repository } from 'typeorm';
import { QueryDictTypeDto } from './dto/query-dict-type.dto';

@Injectable()
export class DictTypeService {
  constructor(
    @InjectRepository(DictType)
    private dictTypeRepository: Repository<DictType>,
  ) {}
  async create(createDictTypeDto: CreateDictTypeDto) {
    const dictTypeData = await this.dictTypeRepository.create(
      createDictTypeDto,
    );
    return this.dictTypeRepository.save(dictTypeData);
  }

  async findAll(queryDictTypeDto: QueryDictTypeDto) {
    const { page, pageSize, dictName, dictCode } = queryDictTypeDto;
    const take = pageSize || 10;
    const skip = ((page || 1) - 1) * take;
    const [data, total] = await this.dictTypeRepository.findAndCount({
      where: {
        ...(dictName && { dictName: Like(`%${dictName}%`) }),
        ...(dictCode && { dictCode: Like(`%${dictCode}%`) }),
      },
      relations: {
        dictItems: true,
      },
      take: take,
      skip: skip,
    });
    return { data, total, page, pageSize };
  }

  async findOne(id: number) {
    return await this.dictTypeRepository.findOne({ where: { id } });
  }

  async update(id: number, updateDictTypeDto: UpdateDictTypeDto) {
    const dictType = await this.findOne(id);
    this.dictTypeRepository.merge(dictType, updateDictTypeDto);
    return this.dictTypeRepository.save(dictType);
  }

  remove(id: number) {
    return this.dictTypeRepository.delete(id);
  }
}
